package com.leonzx.base.controller.userpermission;

import com.leonzx.base.config.pager.Page;
import com.leonzx.base.config.pager.PageInfo;
import com.leonzx.base.controller.base.BaseController;
import com.leonzx.base.entity.system.User;
import com.leonzx.base.entity.email.UserMail;
import com.leonzx.base.service.mail.UserMailService;
import com.leonzx.base.service.system.UserService;
import com.leonzx.base.utils.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author:梁亮
 * @Description:
 * @Date: 2018/6/5 10:53
 */
@RestController
@RequestMapping("/ajax/userpermission/user")
public class AjaxUserController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMailService userMailService;

    /**
     * 人员列表
     *
     * @param user
     * @param page
     * @return
     */
    @RequestMapping("/list")
    @RequiresPermissions("/userpermission/user/list")
    public Map<String, Object> list(User user, @PageInfo(pageSize = Page.PAGE_SIZE, orderBy = "create_time") Page<User> page) {
        Map<String, Object> result = getMap();
        try {
            List<User> users = userService.getAllByUser(user);
            page.setResult(users);
            SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
            //循环list，处理数据
            for (User u : users) {
                String createTimeStr = "";
                if (u.getCreateTime() != null) {
                    createTimeStr = sdf.format(u.getCreateTime());
                }
                String createUserName = userService.getUserNameById(u.getCreateUserId());
                u.setCreateTimeStr(createTimeStr);
                u.setCreateUserName(createUserName);
            }
            result.put("count", page.getTotalCount());
            result.put("data", users);
            result.put("code", "0");
            result.put("msg", "加载完成");
        } catch (Exception e) {
            logger.error("获取用户数据失败", e);
            addFailMessage(result, "获取用户数据失败");
        }
        return result;
    }

    /**
     * 添加新人员账号名称或者更新信息
     *
     * @param user
     * @return
     */
    @RequestMapping("/save")
    @RequiresPermissions("/userpermission/user/list")
    public Map<String, Object> saveorupdate(User user) {
        Map<String, Object> result = getMap();
        try {
            if (StringUtils.isNotBlank(user.getId())) {
                userService.update(user);
                addSuccessMessage(result, "用户更新成功");
            } else {
                user.setCreateUserId(currentUser().getId());
                User user1 = userService.getByUsername(user.getUsername());
                //验证重复
                if (!Objects.isNull(user1)) {
                    addFailMessage(result, "账户已存在");
                } else {
                    userService.insert(user);
                    addSuccessMessage(result, "保存用户成功");
                }
            }
        } catch (Exception e) {
            logger.error("保存用户失败", e);
            addFailMessage(result, "保存用户失败");
        }
        return result;
    }

    /**
     * 禁用用户
     *
     * @param user
     * @return
     */
    @RequestMapping("/del")
    @RequiresPermissions("/userpermission/user/list")
    public Map<String, Object> del(User user) {
        Map<String, Object> result = getMap();
        try {
            user.setState(Constants.STATE_INVAILD);
            userService.changeState(user);
            userService.outLineByUserId(user.getId());
            addSuccessMessage(result, "禁用成功");
        } catch (Exception e) {
            logger.error("禁用失败", e);
            addFailMessage(result, "禁用失败");
        }
        return result;
    }

    /**
     * 启用用户
     *
     * @param user
     * @return
     */
    @RequestMapping("/recover")
    @RequiresPermissions("/userpermission/user/list")
    public Map<String, Object> recover(User user) {
        Map<String, Object> result = getMap();
        try {
            user.setState(1);
            userService.changeState(user);
            addSuccessMessage(result, "启用成功");
        } catch (Exception e) {
            logger.error("禁用失败", e);
            addFailMessage(result, "启用失败");
        }
        return result;
    }

    @RequestMapping("/resetPassword")
    @RequiresPermissions("/userpermission/user/list")
    public Map<String, Object> resetPassword(User user) {
        Map<String, Object> result = getMap();
        try {
            userService.resetPassword(user);
            addSuccessMessage(result,"重置密码成功");
        } catch (Exception e) {
            logger.error("重置密码失败", e);
            addFailMessage(result, "重置密码失败");
        }
        return result;
    }

    @RequestMapping("/userMail")
    public Map<String, Object> userMail(String userId) {
        Map<String, Object> result = getMap();
        try {
            UserMail userMail = userMailService.findUserMailByUserId(userId);
            addSuccessMessage(result, "获取邮箱成功");
            result.put("data", userMail);
        } catch (Exception e) {
            logger.error("获取邮箱失败", e);
            addFailMessage(result, "获取邮箱失败");
        }
        return result;
    }

    /**
     * 保存用户邮箱信息
    *@Author chen
    *@Date 2018/7/6 10:03
    */
    @RequestMapping("/saveUserMail")
    public Map<String, Object> saveUserMail(UserMail userMail){
        Map<String, Object> result = getMap();
        try {
            userMailService.saveUserMail(userMail);
            addSuccessMessage(result, "保存邮箱信息成功");
        } catch (Exception e) {
            logger.error("保存邮箱信息失败", e);
            addFailMessage(result, "保存邮箱信息失败");
        }
        return result;
    }
}